import React, { useEffect, useState } from 'react';
import { Button, Input, Table, PaginationProps, Pagination, Popconfirm, message, Switch } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import type { TableRowSelection } from 'antd/es/table/interface';
import '../../css/reviewer/listItem.scss'
import { reviewerList, reviewerDel,reviewerSwitch } from '../../api/reviewer/reviewer'
import { render } from 'react-dom';
import { useNavigate } from 'react-router-dom';
const ReviewerList = () => {
  // 列表数据类型
  interface DataType {
    key: React.Key;
    reviewer_name: string;
    mobile: number;
    deparmentname: string;
    job: string;
    is_use: any;
  }
  //  分页查询数据类型
  interface IParams {
    page: number;
    pageSize: number;
    idorname?: any;
    mobile?: number;
  }

  // 跳转路由
  const navigate  = useNavigate()
  //  列表数据
  const [data, setDate] = useState<any>()
  //  分页数据
  const [params, setParams] = useState<IParams>({ page: 1, pageSize: 10 })
  // 定义分页的总条数
  let [total, setTotal] = useState(0)
  // 查询关键字
  let [input, setInput] = useState('')
  
  //  调用列表接口
  const reviewerListInfo = async () => {
    const res: any = await reviewerList(params)
    console.log(res);
    total = res.total
    setTotal(res.total)
    setDate(res.data)
  }

  // 列表内容
  const columns: ColumnsType<DataType> = [
    {
      title: '核销人姓名',
      dataIndex: 'reviewer_name',
      width: '15%',
      align: 'center',
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      width: '15%',
      align: 'center'
    },
    {
      title: '部门',
      dataIndex: 'deparmentname',
      width: '15%',
      align: 'center'
    },
    {
      title: '职务',
      dataIndex: 'job',
      width: '15%',
      align: 'center'
    },
    {
      title: '是否启用',
      dataIndex: 'is_use',
      width: '15%',
      align: 'center',
      render: (is_use: any, value: any, index: any) =>{
      // console.log('56789678',text,value, index)
       return  <Switch defaultChecked={is_use === 1 ? true : false} onChange={(checked) => changeSwitch(value,checked)} />
      }
    },
    {
      title: '操作',
      dataIndex: 'id',
      width: '20%',
      align: 'center',
      render: (ids: any, data: any) => (<div>
        <Button type="primary" size="small" className="upda_button" onClick={()=>EditItem(ids)}>修改</Button>
        <Popconfirm
          title="是否确认删除?"
          onConfirm={() => delItem(ids)}
          onCancel={cancel}
          okText="确定"
          cancelText="取消"
        >
          <Button className="del_button" type="primary" size="small" danger>删除</Button>
        </Popconfirm>
      </div>)
    },
  ];

  // 批量删除的id
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  // 复选框
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };

  // 复选框下拉选择
  const rowSelection: TableRowSelection<DataType> = {
    selectedRowKeys,
    onChange: onSelectChange,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
      {
        key: 'odd',
        text: 'Select Odd Row',
        onSelect: (changableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return false;
            }
            return true;
          });
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
      {
        key: 'even',
        text: 'Select Even Row',
        onSelect: (changableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return true;
            }
            return false;
          });
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
    ],
  };

  // 分页
  const onChangePage = (page: number, pageSize: number) => {
    console.log('Page: ',page, pageSize);
    setParams({ ...params, page, pageSize })
  };

  // 获取文本值
  const changeInput = (e: any) => {
    setInput(e.target.value)
  }

  // 查询
  const search = async (val: any) => {
    console.log(val);
    const res: any = await reviewerList({
      idorname: val
    })
    console.log(res.data);
    setDate(res.data)
    setTotal(res.total)
  }

  // 输入关键字查询
  const onkeyup =(e:any)=>{
    // console.log(e);
    if(e.keyCode===13){
      search(input)
    }
  }

  // 删除,点击确定
  const delItem = async (ids: number) => {
    console.log(ids);
    const res: any = await reviewerDel({ id: ids })
    console.log(res);
    if (res.code === '00000') {
      message.success('删除成功');
      reviewerListInfo()//刷新列表
    } else {
      message.error(res.msg)
    }
  }

  // 批量删除
  const delArr = async () => {
    console.log(selectedRowKeys);
    let idarr = selectedRowKeys
    if (idarr.length === 0) {
      message.error('请选择要删除的信息！')
    } else {
      const res: any = await reviewerDel({ id: idarr })
      console.log(res);
      if (res.code === '00000') {
        message.success('删除成功');
        reviewerListInfo()//刷新列表
      } else {
        message.error(res.msg)
      }
    }
  }

  // 删除，点击取消
  const cancel: any = () => {
    message.error('取消删除');
  };

  // switch开关
  const changeSwitch = async(val: any,checked:boolean) => {
  console.log('7777', checked,val)
    // console.log(val);
    let { id } = val
    console.log(id);
    const res:any = await reviewerSwitch({
      id:id,
      is_use:checked
    })
    console.log(res);
    if(res.code==='00000'){
      message.success('修改状态成功');
    }else{
      message.error('修改状态失败')
    }
  };

  // 添加
  const addInfo = ()=>{
    navigate('/index/reviewerAddEdit')
  }

  // 修改
  const EditItem =(ids:any)=>{
    // console.log(ids);
    navigate('/index/reviewerAddEdit?id='+ids)
  }
  // 调用接口
  useEffect(() => {
    reviewerListInfo()//列表接口
  }, [params])
  return (<>
    <div className="listItem">
      <div className="head_input">
        <Input value={input} onChange={changeInput} onKeyUp={onkeyup} style={{ width: '170px' }} placeholder="请输入核销人姓名" />
        <Button type="primary" className='search_button' onClick={() => search(input)}>查询</Button>
        <Button type="primary" className='add_button' onClick={addInfo}>添加</Button>
        <Popconfirm
          title="是否确认删除?"
          onConfirm={delArr}
          onCancel={cancel}
          okText="确定"
          cancelText="取消"
        >
          <Button type="primary" danger>批量删除</Button>
        </Popconfirm>

      </div>

      {/* 列表 */}
      <div className='tableItem'>
        <Table rowKey="id" bordered pagination={false} rowSelection={rowSelection} columns={columns} dataSource={data} />
      </div>

      {/* 分页 */}
      <div className='pagination'>
        <Pagination
          showSizeChanger
          // current={1}
          onChange={onChangePage}
          total={total}
          pageSizeOptions={['5', '10', '15', '20']}
          showTotal={total => `共${total}条数据`}
        />
      </div>
    </div>
  </>);
}

export default ReviewerList;